<!-- 委托列表 -->

<template>
  <div class="delegation-list" ref="listContainer">
    <div class="content-wrapper"
         ref="contentWrapper"
         :style="{ transform: `translateY(${translateY}px)` }">
      <!-- 修改调试信息显示 -->
      <div v-if="filteredDelegations.length === 0" class="no-delegation">
        {{ delegations.length === 0 ? '暂无委托' : '暂无符合筛选条件的委托' }}
      </div>
      <delegation-card
        v-for="delegation in filteredDelegations"
        :key="delegation.order_id"
        :delegation="delegation"
        @click.native="openDelegation(delegation.order_id, $event)"
      />
      <div v-if="filteredDelegations.length != 0" class="loading-area" ref="loadingArea">
        {{ loadingText }}
      </div>
    </div>
    <delegation-popup
      v-model:show="showPopup"
      :delegation="selectedDelegation"
      :clickPosition="clickPosition"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, onBeforeUnmount, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import DelegationCard from '../component/Delegation-card.vue'
import DelegationPopup from '../component/DelegationPopup.vue'
import axios from 'axios'

const router = useRouter()

const pageSize = 10 // 每页10条数据
const currentPage = ref(1)
const delegations = ref([]);

// 添加筛选条件
const filters = ref({
  pickup_address: 'all',
  delivery_address: 'all',
  pickup_type: 'all',
  size: 'all',
  total_amount: 'all',
  custom_range: null
})

// 修改 filteredDelegations 计算属性
const filteredDelegations = computed(() => {
  return delegations.value.filter(delegation => {
    // 检查取件地址
    if (filters.value.pickup_address !== 'all' && 
        delegation.pickup_address !== filters.value.pickup_address) {
      return false
    }

    // 检查送达地址
    if (filters.value.delivery_address !== 'all' && 
        delegation.delivery_address !== filters.value.delivery_address) {
      return false
    }

    // 检查取件类型
    if (filters.value.pickup_type !== 'all' && 
        delegation.pickup_type !== filters.value.pickup_type) {
      return false
    }

    // 检查物件大小
    if (filters.value.size !== 'all' && 
        delegation.size !== filters.value.size) {
      return false
    }

    // 检查委托金额
    if (filters.value.total_amount !== 'all') {
      const amount = delegation.total_amount
      if (filters.value.total_amount === '自定义' && filters.value.custom_range) {
        // 处理自定义范围
        const { min, max } = filters.value.custom_range
        if (amount < min || amount > max) {
          return false
        }
      } else {
        // 处理预设范围
        const [min, max] = filters.value.total_amount.split('-').map(v => 
          parseInt(v.replace('元', '')))
        if (amount < min || amount > max) {
          return false
        }
      }
    }

    return true
  })
})

// 修改状态管理
const pageState = ref({
  currentPage: 1,
  hasMore: true,
  isFirstLoad: true
})

// 修改初始数据加载逻辑
const initializeData = async () => {
  if (!pageState.value.isFirstLoad) return
  
  // 检查 sessionStorage 中是否有已保存的状态
  const savedState = sessionStorage.getItem('delegationListState')
  if (savedState) {
    const state = JSON.parse(savedState)
    delegations.value = state.delegations
    filters.value = state.filters
    pageState.value = state.pageState
    scrollPosition.value = state.scrollPosition
    
    // 恢复滚动位置
    nextTick(() => {
      if (listContainer.value) {
        listContainer.value.scrollTop = scrollPosition.value
      }
    })
    return
  }

  // 如果没有保存的状态，则从服务器加载数据
  try {
    const response = await axios.get('api/auth/delegates', {
      params: { page: 1 },
      headers: {
        'Authorization': localStorage.getItem('token'),
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.code === 0 && response.data.data?.orders) {
      delegations.value = response.data.data.orders.map(order => ({
        order_id: order.OrderID,
        sender_id: order.SUID,
        receiver_id: order.RUID,
        pickup_type: order.PickupType,
        pickup_method: order.PickupMethod,
        pickup_address: order.PickupAddress,
        delivery_address: order.DeliveryAddress,
        size: order.Size,
        limit_time: new Date(order.LimitTime),
        phone_number: order.PhoneNumber,
        remarks: order.Remarks,
        detail: order.Detail,
        total_amount: parseFloat(order.TotalAmount),
        status: order.Status,
        created_at: new Date(order.CreatedAt),
        completed_at: order.CompletedAt ? new Date(order.CompletedAt) : null,
        star: order.Star,
        img: order.Img,
        sender: order.Sender,
        receiver: order.Receiver
      }))
      pageState.value.isFirstLoad = false
      pageState.value.hasMore = true
    }
  } catch (error) {
    console.error('获取委托列表失败:', error)
    delegations.value = []
  }
}

// 添加保存状态的函数
const saveState = () => {
  const state = {
    delegations: delegations.value,
    filters: filters.value,
    pageState: pageState.value,
    scrollPosition: listContainer.value ? listContainer.value.scrollTop : 0
  }
  sessionStorage.setItem('delegationListState', JSON.stringify(state))
}

const showPopup = ref(false)
const selectedDelegation = ref(null)
const clickPosition = ref(null)

// 修改点击事件
const openDelegation = (delegationId, event) => {
  console.log('openDelegation被调用', delegationId, event)
  
  // 确保能找到对应的委托数据
  const delegation = delegations.value.find(d => d.order_id === delegationId)
  
  if (delegation) {
    console.log('找到委托数据:', delegation)
    
    // 计算点击位置
    const listRect = listContainer.value.getBoundingClientRect()
    clickPosition.value = {
      left: event ? event.clientX - listRect.left : 0,
      top: event ? event.clientY - listRect.top : 0,
      width: listRect.width,
      height: listRect.height
    }
    
    // 设置选中的委托并显示弹窗
    selectedDelegation.value = delegation
    showPopup.value = true
    
    console.log('弹窗状态:', {
      showPopup: showPopup.value,
      selectedDelegation: selectedDelegation.value,
      clickPosition: clickPosition.value
    })
  } else {
    console.error('未找到对应的委托数据:', delegationId)
  }
}

const listContainer = ref(null)
const contentWrapper = ref(null)
const isLoading = ref(false)
const loadingText = ref('上滑加载更多')
const translateY = ref(0)
let startY = 0
let currentY = 0

// 添加新的响应式变量来存储滚动位置
const scrollPosition = ref(0)

// 修改触摸事件处理函数
const handleTouchStart = (e) => {
  const container = listContainer.value
  const scrollTop = container.scrollTop
  const scrollHeight = container.scrollHeight
  const clientHeight = container.clientHeight

  // 只在接近底部时才开始处理触摸事件
  if (scrollTop + clientHeight >= scrollHeight - 110) {
    startY = e.touches[0].clientY
    currentY = startY
  }
}

// 修改触摸处理逻辑
const handleTouchMove = (e) => {
  if (isLoading.value) return
  
  const container = listContainer.value
  const scrollTop = container.scrollTop
  const scrollHeight = container.scrollHeight
  const clientHeight = container.clientHeight
  currentY = e.touches[0].clientY
  const delta = currentY - startY

  // 处理上滑加载（在底部）
  if (scrollTop + clientHeight >= scrollHeight - 110) {
    if (delta < 0) {
      const pullDistance = Math.abs(delta)
      translateY.value = -Math.pow(pullDistance * 0.2, 0.8)
      
      if (pullDistance > 500) {
        loadingText.value = '释放立即加载'
        e.preventDefault()
      } else {
        loadingText.value = '上滑加载更多'
      }
    }
  }
}

// 修改触摸结束处理函数
const handleTouchEnd = async () => {
  if (isLoading.value) return

  const container = listContainer.value
  const scrollTop = container.scrollTop
  const scrollHeight = container.scrollHeight
  const clientHeight = container.clientHeight
  
  // 判断是否在底部且显示加载提示
  const isNearBottom = scrollTop + clientHeight >= scrollHeight - 110
  const shouldLoad = loadingText.value === '释放立即加载'

  if (isNearBottom && shouldLoad) {
    await loadMore()
  }

  translateY.value = 0
  if (!isLoading.value) {
    loadingText.value = pageState.value.hasMore ? '上滑加载更多' : '没有更多数据了'
  }
}

// 修改数据加载方法
const loadMore = async () => {
  if (isLoading.value || !pageState.value.hasMore) return

  try {
    isLoading.value = true
    loadingText.value = '加载中...'
    
    const response = await axios.get('api/auth/delegates', {
      params: { page: pageState.value.currentPage + 1 },
      headers: {
        'Authorization': localStorage.getItem('token'),
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 0 && response.data.data?.orders) {
      const newOrders = response.data.data.orders.map(order => ({
        order_id: order.OrderID,
        sender_id: order.SUID,
        receiver_id: order.RUID,
        pickup_type: order.PickupType,
        pickup_method: order.PickupMethod,
        pickup_address: order.PickupAddress,
        delivery_address: order.DeliveryAddress,
        size: order.Size,
        limit_time: new Date(order.LimitTime),
        phone_number: order.PhoneNumber,
        remarks: order.Remarks,
        detail: order.Detail,
        total_amount: parseFloat(order.TotalAmount),
        status: order.Status,
        created_at: new Date(order.CreatedAt),
        completed_at: order.CompletedAt ? new Date(order.CompletedAt) : null,
        star: order.Star,
        img: order.Img,
        sender: order.Sender,
        receiver: order.Receiver
      }))

      if (newOrders.length > 0) {
        delegations.value = [...delegations.value, ...newOrders]
        pageState.value.currentPage += 1
        loadingText.value = '加载成功'
      } else {
        pageState.value.hasMore = false
        loadingText.value = '没有更多数据了'
      }
    } else {
      loadingText.value = '加载失败'
    }
    
    await new Promise(resolve => setTimeout(resolve, 500))
  } catch (error) {
    console.error('Failed to load more:', error)
    loadingText.value = '加载失败'
  } finally {
    isLoading.value = false
    translateY.value = 0
  }
}

// 在组件挂载时恢复数据
onMounted(async () => {
  await initializeData()
  
  const container = listContainer.value
  if (container) {
    container.addEventListener('touchstart', handleTouchStart, { passive: false })
    container.addEventListener('touchmove', handleTouchMove, { passive: false })
    container.addEventListener('touchend', handleTouchEnd)
    
    // 监听滚动事件以保存位置
    container.addEventListener('scroll', () => {
      scrollPosition.value = container.scrollTop
    })
  }
})

// 在组件即将卸载时清理事件监听
onBeforeUnmount(() => {
  // 在路由变化时保存状态
  if (router.currentRoute.value.name !== 'DelegationDetail') {
    saveState()
  }
})

// 添加页面刷新事件处理
const handleBeforeUnload = () => {
  // 在页面刷新时清除 sessionStorage
  sessionStorage.removeItem('delegationListState')
}

onMounted(() => {
  window.addEventListener('beforeunload', handleBeforeUnload)
})

onUnmounted(() => {
  const container = listContainer.value
  if (container) {
    container.removeEventListener('touchstart', handleTouchStart)
    container.removeEventListener('touchmove', handleTouchMove)
    container.removeEventListener('touchend', handleTouchEnd)
    container.removeEventListener('scroll', () => {})
  }
  window.removeEventListener('beforeunload', handleBeforeUnload)
})
</script>

<style scoped>
.delegation-list {
  padding: 1rem;
  background: #ffffff;
  height: 100%;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  overscroll-behavior: contain; /* 添加这行来防止iOS的橡皮筋效果 */
  touch-action: pan-y pinch-zoom; /* 添加这行来优化触摸行为 */
}

.content-wrapper {
  min-height: 100%;
  padding-bottom: 40px;
  transition: transform 0.3s cubic-bezier(0.23, 1, 0.32, 1);
  will-change: transform;
}

.no-delegation {
  padding: 15px 0;
  margin-bottom: 100px;
  text-align: center;
  color: #666;
  font-size: 14px;
}

.loading-area {
  padding: 15px 0;
  margin-bottom: 100px;
  text-align: center;
  color: #666;
  font-size: 14px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

</style>